#include "TcpBusiness.h"
#include <QtNetwork>

TcpBusiness::TcpBusiness(qintptr socketDescriptor, QObject *parent)
	: QObject(parent)
	, m_tcpSocket(nullptr)
	, m_socketDescriptor(socketDescriptor)
{
	qDebug() << "TcpBusiness main thread" << QThread::currentThread() << QThread::currentThreadId() << this->thread();
}

TcpBusiness::~TcpBusiness()
{}

void TcpBusiness::creatConn()
{
	qDebug() << "TcpBusiness creatConn thread" << QThread::currentThread() << QThread::currentThreadId() << this->thread();

	m_tcpSocket = new QTcpSocket(this);
	if (!m_tcpSocket->setSocketDescriptor(m_socketDescriptor))
	{
		emit error(m_tcpSocket->error());

		delete m_tcpSocket;
		m_tcpSocket = nullptr;
		return;
	}

	connect(m_tcpSocket, &QTcpSocket::disconnected, m_tcpSocket, &QTcpSocket::deleteLater);
	connect(m_tcpSocket, &QTcpSocket::readyRead, this, &TcpBusiness::echo);
}

void TcpBusiness::echo()
{
	qDebug() << "TcpBusiness echo thread" << QThread::currentThread() << QThread::currentThreadId() << this->thread();

	if (!m_tcpSocket)
		return;

	QByteArray data = m_tcpSocket->readAll();
	if (!data.isEmpty())
	{
		m_tcpSocket->write(data);
	}
}
